package com.pubinfo.passbook.common.service.master.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.entity.TRuleDistrict;
import com.pubinfo.passbook.common.entity.TRuleFormula;
import com.pubinfo.passbook.common.mapper.TRuleDistrictMapper;
import com.pubinfo.passbook.common.mapper.TRuleFormulaMapper;
import com.pubinfo.passbook.common.model.dto.rule.RuleFormulaParam;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.service.master.TRuleFormulaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
@Slf4j
public class TRuleFormulaServiceImpl extends ServiceImpl<TRuleFormulaMapper, TRuleFormula>
    implements TRuleFormulaService {
  
  @Resource
  private TRuleDistrictMapper districtMapper;
  
  @Override
  public Map<String, TRuleFormula> findFormulaByDistrictId(String districtId) {
  
    Map<String, TRuleFormula> tRuleFormulaMap = new HashMap<>();
    List<TRuleFormula> tRuleFormulas = this.baseMapper.findFormulaByDistrictId(districtId);
    if (CollectionUtils.isEmpty(tRuleFormulas)) {
    
      return tRuleFormulaMap;
    }
    for (TRuleFormula ruleFormula : tRuleFormulas) {
      tRuleFormulaMap.put(ruleFormula.getFormulaKey(), ruleFormula);
    }
    return tRuleFormulaMap;
  }
  

  @Override
  public boolean saveFormula(TRuleFormula formula) {
    TRuleDistrict district = districtMapper.selectById(formula.getDistrictId());
    if (district != null)
      return this.baseMapper.insert(formula) > 0;
    return false;
  }

  @Override
  public JsonResult<String> updateRuleFormula(TRuleFormula formula) {
    TRuleDistrict district = districtMapper.selectById(formula.getDistrictId());
    if (district == null)
      return JsonResult.error("没有相关的district信息,更新失败");
    this.baseMapper.updateById(formula);
    return JsonResult.success("更新成功");
  }

  @Override
  public IPage<TRuleFormula> selectRuleFormula(RuleFormulaParam param) {
    IPage<TRuleFormula> iPage = page(param.getPage("create_time"));
    return this.baseMapper.selectRuleFormula(iPage, param);
  }
  
}




